/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package backupit.core.io;

import backupit.core.FileInfo;
import backupit.core.FileInfoSet;
import backupit.core.DefaultFileInfoComparator;
import java.io.File;
import java.util.Arrays;

/**
 *
 * @author dbotelho
 */
public class FileInfoSetReader {
    
    private Boolean hidden;
    private Boolean recursive;
    private Boolean update;
    private String root;
        
    public FileInfoSetReader(String root,Boolean modifiable,Boolean hidden,Boolean recursive){
        this.root = root;
        this.hidden = hidden;
        this.recursive = recursive;
        this.update = modifiable;
    }
    
    public FileInfoSet loadFiles() { 
        return loadFiles(new File(getRoot()));
    }
    
    private FileInfoSet loadFiles(File file) {
            
        FileInfoSet source = new FileInfoSet(new DefaultFileInfoComparator(update));

        fecthFiles(source,file);
        file = null;
        System.gc();
        
        return source;
    }

    private void fecthFiles(FileInfoSet source,File path) {

        File files[];
        
        files = path.listFiles();
        try {
            Arrays.sort(files);
            for (int i = 0,  n = files.length; i < n; i++) {
                if (!files[i].isDirectory() || (files[i].isDirectory() && this.recursive) ) {
                    if (!(!hidden && files[i].isHidden())) {


                        FileInfo entry = FileInfo.parse(files[i]);
                        entry.setRelativePath(entry.getAbsolutePath().substring(getRoot().length()));
                        source.add(entry);

                        if (this.recursive && files[i].isDirectory()) {
                            fecthFiles(source, files[i]);
                        }
                    }
                }
            }
        } catch (java.lang.NullPointerException ex) {
            ex.printStackTrace();
        }
    }

    public String getRoot() {
        return root;
    }
    

}
